package com.ruoyi.txxmember.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.HttpUtils;
import com.ruoyi.common.core.utils.PhoneFormatCheckUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;

import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.txxmember.LoginFrom.LoginUser;
import com.ruoyi.txxmember.LoginFrom.RegisterUser;
import com.ruoyi.common.core.constant.AliConstant;
import com.ruoyi.common.core.domain.Member;
import com.ruoyi.txxmember.idCard.ResponseEntity;
import com.ruoyi.txxmember.mapper.MemberMapper;
import com.ruoyi.txxmember.service.IMemberService;
import com.ruoyi.txxmember.vo.AliSmsVo;
import com.ruoyi.txxmember.vo.IdCardVo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements IMemberService {


    @Resource
    private RedisService redisService;

    @Autowired
    private TokenService tokenService;

    /**
     * 注册
     * @param registerUser
     */
    @Override
    public void register(RegisterUser registerUser) {
        boolean phoneLegal = PhoneFormatCheckUtils.isChinaPhoneLegal(registerUser.getPhonenumber());
        if(!phoneLegal){
            throw new ServiceException("手机号格式不正确，请重新输入");
        }
        Object o = redisService.get(registerUser.getPhonenumber());
        if(ObjectUtils.isEmpty(o)){
            throw new ServiceException("当前验证码已过期或不存在请重新输入，或请检查手机号是否输入正确");
        }
        if(!registerUser.getCode().equals(o.toString())){
            throw new ServiceException("您输入的验证码有误，请重新输入");
        }
        LambdaQueryWrapper<Member> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Member::getPhonenumber, registerUser.getPhonenumber());
        Member member1 = this.getOne(lambdaQueryWrapper);
        if(!ObjectUtils.isEmpty(member1)){
            throw new ServiceException("当前用户已注册，请直接登录");
        }
        Member member = new Member();
        BeanUtils.copyProperties(registerUser,member);
        member.setStatus("0");
        member.setTradingPassword(registerUser.getPassword());
        member.setNickName(registerUser.getUserName());
        //随机6位ID
        member.setUserCode(StringUtils.sixRamdomCode());
        this.save(member);
    }

    /**
     * 发短信
     * @param phonenumber
     */
    @Override
    public void sendsms(String phonenumber) {
        boolean phoneLegal = PhoneFormatCheckUtils.isChinaPhoneLegal(phonenumber);
        if(!phoneLegal){
            throw new ServiceException("手机号格式不正确，请重新输入");
        }

        //模拟获得6位验证码
        Object o = redisService.get(phonenumber);
        if(!ObjectUtils.isEmpty(o)){
            redisService.del(phonenumber);
        }
        //TODO 阿里云发送短信
        String smsCode = this.aliSmsSend(phonenumber);
        redisService.set(phonenumber,smsCode,60*5);
    }

    /**
     * 阿里云短信发送
     * @return
     */
    public String aliSmsSend(String phonenumber){
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(AliConstant.ACCESS_KEYID)
                // 您的AccessKey Secret
                .setAccessKeySecret(AliConstant.ACCESS_KEY_SECRET);
                // 访问的域名
        //config.endpoint = "dysmsapi.aliyuncs.com";
        try {
            Client client = new Client(config);
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.setPhoneNumbers(phonenumber);
            sendSmsRequest.setSignName(AliConstant.SING_NAME);
            sendSmsRequest.setTemplateCode(AliConstant.TEMPLATE_CODE);
            String smsCode = StringUtils.sixRamdomCode();
            AliSmsVo aliSmsVo = new AliSmsVo();
            aliSmsVo.setCode(smsCode);
            String aliSmsCode = JSON.toJSONString(aliSmsVo);
            sendSmsRequest.setTemplateParam(aliSmsCode);
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            return smsCode;
        }catch (Exception e){
            throw new ServiceException("短信验证码发送失败");
        }


    }

    /**
     * 登录
     * @param loginUser
     */
    @Override
    public AjaxResult login(LoginUser loginUser) {
        LambdaQueryWrapper<Member> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Member::getUserName, loginUser.getUserName());
        Member member = this.getOne(lambdaQueryWrapper);
        if(ObjectUtils.isEmpty(member)){
            throw new ServiceException("当前用户不存在");
        }
        if(!loginUser.getPassword().equals(member.getPassword())){
            throw new ServiceException("您输入的密码有误，请重新输入");
        }
        return AjaxResult.success("登录成功",tokenService.createToken(member));
    }

    /**
     * 修改登录密码
     * @param oldPwd
     * @param newPwd
     */
    @Override
    public void updateLoginPassword(String oldPwd, String newPwd,String loginId) {
        if(StringUtils.isEmpty(loginId)){
            throw new ServiceException("当前登录已失效，请重新登录");
        }
        if(StringUtils.isEmpty(newPwd)){
            throw new ServiceException("新密码不能为空");
        }
        LambdaQueryWrapper<Member> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Member::getId,loginId)
                .and(i->i.eq(Member::getPassword,oldPwd));
        Member member = this.getOne(lambdaQueryWrapper);
        if(ObjectUtils.isEmpty(member)){
            throw new ServiceException("请检查您输入的登录密码是否正确");
        }
        member.setPassword(newPwd);
        this.updateById(member);
    }

    /**
     * 修改交易密码
     * @param oldTradingPwd
     * @param newTradingPwd
     * @param loginId
     */
    @Override
    public void updateTradingPassword(String oldTradingPwd, String newTradingPwd, String loginId) {
        if(StringUtils.isEmpty(loginId)){
            throw new ServiceException("当前登录已失效，请重新登录");
        }
        if(StringUtils.isEmpty(newTradingPwd)){
            throw new ServiceException("新密码不能为空");
        }
        LambdaQueryWrapper<Member> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Member::getId,loginId)
                .and(i->i.eq(Member::getTradingPassword,oldTradingPwd));
        Member member = this.getOne(lambdaQueryWrapper);
        if(ObjectUtils.isEmpty(member)){
            throw new ServiceException("请检查您输入的交易密码是否正确");
        }
        member.setTradingPassword(newTradingPwd);
        this.updateById(member);
    }

    /**
     * 忘记交易密码
     * @param phoneNum
     * @param newPwd
     * @param code
     * @param loginId
     */
    @Override
    public void forgetTradingPassword(String phoneNum, String newPwd,String code, String loginId) {
        String codeNum = redisService.getCacheObject(phoneNum);
        if(StringUtils.isEmpty(loginId)){
            throw new ServiceException("当前登录已失效，请重新登录");
        }
        if(StringUtils.isEmpty(code)){
            throw new ServiceException("验证码不能为空，请输入验证码");
        }
        if(StringUtils.isEmpty(codeNum)){
            throw new ServiceException("当前验证码已过期");
        }
        if(!code.equals(codeNum)){
            throw new ServiceException("您输入的验证码有误，请重新输入");
        }
        LambdaQueryWrapper<Member> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Member::getId,loginId)
                .and(i->i.eq(Member::getPhonenumber,phoneNum));
        Member member = this.getOne(lambdaQueryWrapper);
        if(ObjectUtils.isEmpty(member)){
            throw new ServiceException("重置失败，请检查是否手机号输入错误");
        }
        member.setTradingPassword(newPwd);
        this.updateById(member);
    }

    /**
     * 用户信息
     * @param loginId
     * @return
     */
    @Override
    public Member memberInfo(String loginId) {
        if(StringUtils.isEmpty(loginId)){
            throw new ServiceException("当前用户登录已失效，请重新登录");
        }
        Member member = this.getById(loginId);
        return member;
    }

    /**
     * 退出登录
     */
    @Override
    public AjaxResult loginout(String loginId) {
        Member member = this.getById(loginId);
        if (StringUtils.isNotNull(member))
        {
            // 删除用户缓存记录
            tokenService.delLoginUser(member.getToken());
            return AjaxResult.success("退出成功");
        }
        return AjaxResult.error();
    }

    /**
     * 身份证验证
     * @param idCardVo
     */
    @Override
    public void idCardValidation(IdCardVo idCardVo) {
        //先验证二要素
//        ResponseEntity responseEntity = this.validationTwoInfo(idCardVo.getCardNo(), idCardVo.getRealName());
//        if(responseEntity.getError_code()!=0){
//            throw new ServiceException("验证失败，请检查身份证号和姓名是否一致");
//        }
//        if( !responseEntity.getResult().getIsok()){
//            throw new ServiceException("验证失败，请检查身份证号和姓名是否一致");
//        }
        //验证正面
        this.validationPositive();
        //验证反面
        this.validationReverse();
    }
    /**
     * 二要素验证
     * @param cardNo
     * @param realName
     */
    public ResponseEntity validationTwoInfo(String cardNo, String realName){
        String host = AliConstant.HOST;
        String path = AliConstant.TWO_PATH;
        String method = "GET";
        String appcode = AliConstant.APPCODE;
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("cardNo", cardNo);
        querys.put("realName", realName);
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            //获取response的body
            String body = EntityUtils.toString(response.getEntity());
            ResponseEntity responseEntity = JSON.parseObject(body,ResponseEntity.class);
            return responseEntity;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 正面验证
     */
    public ResponseEntity validationPositive(){
        String host =  AliConstant.HOST;
        String path = AliConstant.POSITIVE_PATH;
        String method = "POST";
        String appcode = AliConstant.APPCODE;
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("base64Str", "base64Str");
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //获取response的body
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 反面验证
     */
    public ResponseEntity validationReverse(){
        String host =  AliConstant.HOST;
        String path = AliConstant.REVERSE_PATH;
        String method = "POST";
        String appcode = AliConstant.APPCODE;
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("base64Str", "base64Str");
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //获取response的body
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
